# 自定义异常处理
import json

from django.http import Http404
from rest_framework.exceptions import PermissionDenied
from rest_framework.views import set_rollback
from rest_framework import exceptions

from utils.response import APIResponse


def custom_exception_handler(exc, content):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            # data = [i for i in exc.detail.values()][0]
            msg = [i for i in exc.detail.values()][0][0]
        else:
            # data = {'detail': exc.detail}
            msg = exc.detail

        set_rollback()
        return APIResponse(msg=msg, data_status=exc.status_code, headers=headers)

    return None
    # # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    # response = exception_handler(exc, context)
    # # 如果response响应对象为空，则设置message这个key的值，并将状态码设为500
    # # 如果response响应对象不为空，则则设置message这个key的值，并将使用其本身的状态码
    # if response is None:
    #     return APIResponse(
    #         data_status=status.HTTP_500_INTERNAL_SERVER_ERROR,
    #         msg="服务器错误",
    #         results=f"{exc}"
    #     )
    #
    # else:
    #     obj = {}
    #     print(exc.__dict__)
    #     if hasattr(exc, 'detail'):
    #         for key, value in exc.detail.items():
    #             obj[key] = f"{value[0]}"
    #             return APIResponse(
    #                 data_status=exc.status_code,
    #                 msg=[i for i in obj.values()][0]
    #             )
    #     else:
    #         return APIResponse(
    #             msg=exc
    #         )
